package com.rgbgame.physics;

import org.jbox2d.dynamics.ContactListener;


/**
 * Stores contact points away for inspection, as with CCD
 * contacts may be gone by the end of a step.
 * 
 */
class ConcreteContactListener implements ContactListener {
	private PhysicsHandler physicsHandler;
	
	ConcreteContactListener(PhysicsHandler physicsHandler) {
		this.physicsHandler = physicsHandler;
	}
	
	public void emit(ContactEventDispatcher ced) {
		RGBContactPoint[] cpa = this.physicsHandler.m_points;
		int nPoints = this.physicsHandler.m_pointCount;
		for (int i=0; i<nPoints; ++i) {
			ced.dispatchEvent(cpa[i]);
		}
	}
	
	public void add(org.jbox2d.dynamics.contacts.ContactPoint point) {
		if (this.physicsHandler.m_pointCount == PhysicsHandler.k_maxContactPoints) {
			return;
		}

		RGBContactPoint cp = this.physicsHandler.m_points[this.physicsHandler.m_pointCount];
		cp.shape1 = point.shape1;
		cp.shape2 = point.shape2;
		cp.position = point.position.clone();
		cp.normal = point.normal.clone();
		cp.normalForce = point.normalForce;
		cp.tangentForce = point.tangentForce;
		cp.state = 0;

		++this.physicsHandler.m_pointCount;	
	}
	public void persist(org.jbox2d.dynamics.contacts.ContactPoint point) {
		if (this.physicsHandler.m_pointCount == PhysicsHandler.k_maxContactPoints) {
			return;
		}

		RGBContactPoint cp = this.physicsHandler.m_points[this.physicsHandler.m_pointCount];
		cp.shape1 = point.shape1;
		cp.shape2 = point.shape2;
		cp.position = point.position.clone();
		cp.normal = point.normal.clone();
		cp.normalForce = point.normalForce;
		cp.tangentForce = point.tangentForce;
		cp.state = 1;

		++this.physicsHandler.m_pointCount;
	}
	public void remove(org.jbox2d.dynamics.contacts.ContactPoint point) {
		if (this.physicsHandler.m_pointCount == PhysicsHandler.k_maxContactPoints) {
			return;
		}

		RGBContactPoint cp = this.physicsHandler.m_points[this.physicsHandler.m_pointCount];
		cp.shape1 = point.shape1;
		cp.shape2 = point.shape2;
		cp.position = point.position.clone();
		cp.normal = point.normal.clone();
		cp.normalForce = point.normalForce;
		cp.tangentForce = point.tangentForce;
		cp.state = 2;

		++this.physicsHandler.m_pointCount;
	}
}